<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="../../favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="图片对比器">
    <meta name="description" content="js图片对比器">
    <title>图片对比器</title>

    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
<header>图片对比器（兼容移动端，可自适应）</header>

<main>
    <div class="main-img">
        <div id="imgContainer" class="img-container">
            <img id="oldImg" class="old-img" src="" alt="">
            <div id="newWrap" class="new-wrap">
                <img id="newImg" class="new-img" src="" alt="">
            </div>
            <div id="control">
                <div></div>
                <img src="./img/drag.png" alt="">
            </div>
            <div id="tip" class="tip">优化后</div>
        </div>
        <div id="loading" class="loading"></div>
    </div>

    <button onclick="changeImg()">切换图片</button>
</main>

</body>

<script>
	const imageContainerDom = document.querySelector("#imgContainer");
	const oldImgDom = document.querySelector("#oldImg");
	const newWrapDom = document.querySelector("#newWrap");
	const newImgDom = document.querySelector("#newImg");
	const controlDom = document.querySelector("#control");
	const tipDom = document.querySelector("#tip");
	const loadingDom = document.querySelector("#loading");

	const init = (oldImg = './img/o2.jpg', newImg = './img/n2.jpg') => {
		loadingDom.style.display = 'block'
		controlDom.style.opacity = '0'
		tipDom.style.opacity = '0'

        /* 优化体验 */
		oldImgDom.style.opacity = '0'
		newWrapDom.style.opacity = '0'

		oldImgDom.src = oldImg
		newImgDom.src = newImg

		oldImgDom.onload = () => {
			/* 获取图片原始宽高 */
			const imgOriginalW = oldImgDom.naturalWidth
			const imgOriginalH = oldImgDom.naturalHeight

			/* 长边适配，计算图片缩放比例 */
			const imageContainerRatio = imageContainerDom.offsetWidth / imageContainerDom.offsetHeight
			const imgRatio = imgOriginalW / imgOriginalH

			if (imageContainerRatio >= imgRatio) {
				const imgW =  (imageContainerDom.offsetHeight / imgOriginalH) * imgOriginalW;

				/* 设置新图、旧图宽高 */
				oldImgDom.style.width = imgW + 'px'
				oldImgDom.style.height = imageContainerDom.offsetHeight + 'px'
				newImgDom.style.width = imgW + 'px'
				newImgDom.style.height = imageContainerDom.offsetHeight + 'px'

				/* 设置新图位置 */
				newImgDom.style.left = (imageContainerDom.offsetWidth - imgW) / 2 + 'px'
				newImgDom.style.top = '0'
			} else {
				const imgH = (imageContainerDom.offsetWidth / imgOriginalW) * imgOriginalH;

				/* 设置新图、旧图宽高 */
				oldImgDom.style.width = imageContainerDom.offsetWidth + 'px'
				oldImgDom.style.height = imgH + 'px'
				newImgDom.style.width = imageContainerDom.offsetWidth + 'px'
				newImgDom.style.height = imgH + 'px'

				/* 设置新图位置 */
				newImgDom.style.left = '0'
				newImgDom.style.top = (imageContainerDom.offsetHeight - imgH) / 2 + 'px'
			}



			setTimeout(() => {
				oldImgDom.style.opacity = '1'
				newWrapDom.style.opacity = '1'
				loadingDom.style.display = 'none'
				controlDom.style.opacity = '1'
				tipDom.style.opacity = '1'
			}, 500)

			controlDom.addEventListener("mousedown", (e) => {
				document.addEventListener("mousemove", onMouseMove);
				document.addEventListener("mouseup", onMouseUp);
			});

			function onMouseUp() {
				document.removeEventListener("mousemove", onMouseMove);
				document.removeEventListener("mouseup", onMouseUp);
			}

			/* 触摸拖拽 */
			controlDom.addEventListener("touchstart", (e) => {
				document.addEventListener("touchmove", onMouseMove);
				document.addEventListener("touchend", onTouchend);
			});

			function onTouchend() {
				document.removeEventListener("touchmove", onMouseMove);
				document.removeEventListener("touchend", onTouchend);
			}

			function onMouseMove(e) {
				e.preventDefault();

				/* 计算鼠标距离当前父元素左侧的距离 */
				const clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX
				const contentLeft = imageContainerDom.getBoundingClientRect().left
				let offsetX = clientX - contentLeft;

				/* 边界检测，最小为0， 最大为3320px（图片的宽度） */
				if (offsetX < 0) offsetX = 0
				if (offsetX > imageContainerDom.offsetWidth) offsetX = imageContainerDom.offsetWidth

				/* 设置控件的位置，要考虑到控件自身的宽度 */
				controlDom.style.left = `${ offsetX - controlDom.offsetWidth / 2 }px`;
				/* 设置提示框位置 */
				tipDom.style.left = `${ offsetX - tipDom.offsetWidth }px`;
				/* 设置新图容器的宽度 */
				newWrapDom.style.width = offsetX + "px";
			}

			/* 初始化时重置控件位置 */
			controlDom.style.left = `${ imageContainerDom.offsetWidth / 2 - controlDom.offsetWidth / 2 }px`;
			tipDom.style.left = `${ imageContainerDom.offsetWidth / 2 - tipDom.offsetWidth }px`;
			newWrapDom.style.width = imageContainerDom.offsetWidth / 2 + "px";

		}

		oldImgDom.onerror = () => {
			loadingDom.style.display = 'none'
            alert('图片加载失败')
        }
    }

	/* 初次调用 */
	init()

	let timer = null
	window.addEventListener("resize", () => {
		if (timer) clearTimeout(timer)

		timer = setTimeout(() => init(), 200)
	});

	const changeImg = () => {
		if (oldImgDom.src.includes('o1')) return init()

        init('./img/o1.jpg', './img/n1.png')
    }
</script>
</html>
